package cn.itlight.pet.service.impl;

import cn.itlight.basic.exception.BusinessException;
import cn.itlight.basic.utils.BaiduAuditUtils;
import cn.itlight.basic.utils.CodeGenerateUtils;
import cn.itlight.basic.utils.DistanceUtil;
import cn.itlight.basic.utils.Point;
import cn.itlight.order.domain.OrderPetAcquisition;
import cn.itlight.order.mapper.OrderPetAcquisitionMapper;
import cn.itlight.org.domain.Shop;
import cn.itlight.org.mapper.ShopMapper;
import cn.itlight.pet.domain.*;
import cn.itlight.pet.dto.HandlerMsgDto;
import cn.itlight.pet.mapper.PetMapper;
import cn.itlight.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itlight.pet.mapper.SearchMasterMsgMapper;
import cn.itlight.pet.service.ISearchMasterMsgService;
import cn.itlight.basic.service.impl.BaseServiceImpl;
import cn.itlight.user.domain.User;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomliu
 * @since 2022-07-19
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public void publish(SearchMasterMsg searchMasterMsg) {
        // 先保存寻主信息
        searchMasterMsgMapper.save(searchMasterMsg);
        // 文字审核
        StringBuffer sbf = new StringBuffer();
        sbf.append(searchMasterMsg.getName())
                .append(searchMasterMsg.getCoatColor())
                .append(searchMasterMsg.getTitle())
                .append(searchMasterMsg.getAddress());
        if(!BaiduAuditUtils.TextCensor(sbf.toString())){
            // 修改searchMasterMsg的状态
            searchMasterMsg.setState(0);
            // 创建日志对象方便新增
            SearchMasterMsgAuditLog msg = new SearchMasterMsgAuditLog();
            msg.setMsgId(searchMasterMsg.getId());
            msg.setAuditTime(new Date());
            msg.setNote("文字审核失败，可能失败的原因：宠物毛色、寻主标题、地址、宠物名称等有违规字眼");
            searchMasterMsgAuditLogMapper.save(msg);
        } else{
            // 修改searchMasterMsg的状态
            searchMasterMsg.setState(1);
            // 审核通过就查询是否有五十公里内的店铺
            List<Shop> shops = shopMapper.loadAll();
            // 获取用户上传地址坐标
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            // 调用工具类计算得到50公里内最近的店铺
            Shop shop = DistanceUtil.getNearestShop(point, shops);
            // 如果有就推送给店铺，并且绑定
            if (shop != null){
                // 把当前寻主消息绑定给店铺
                searchMasterMsg.setShopId(shop.getId());
            }
        }
        // 5.修改寻主消息，就是修改的寻主状态状态
        searchMasterMsgMapper.update(searchMasterMsg);
    }

    @Override
    public void accept(HandlerMsgDto handlerMsgDto) {
        // 根据msgid和订单是否是取消状态查询订单
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadByMsgIdAndNotCanceled(handlerMsgDto.getMsgId());
        // 如果查询到了收购单，那么说明此消息已被接单，提示用户
        if (orderPetAcquisition != null){
            throw new BusinessException("此消息已被接单！");
        }
        //  2.生成宠物基本信息，详情数据可以等店铺上架时，再进行生成
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(handlerMsgDto.getMsgId());
        Pet pet = msg2Pet(searchMasterMsg);
        petMapper.save(pet);

        // 3.生成收购单信息
        // initOrderPetAcquisition(pet);
        orderPetAcquisition = initOrderPetAcquisition(handlerMsgDto, searchMasterMsg, pet);
        orderPetAcquisitionMapper.save(orderPetAcquisition);
    }

    /*
    * @Title: reject
    * @Description: 拒接
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/20 17:56
    * @Parameters:
    * @Return
    */
    @Override
    public void reject(Long id) {
        // 1.将寻主消息所绑定的店铺Id设置为null
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(id);
        if (searchMasterMsg == null){
            throw new BusinessException("此订单不存在！");
        }
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
    }

    /*
    * @Title: initOrderPetAcquisition
    * @Description: 生成收购单信息
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/20 16:55
    * @Parameters:
    * @Return
    */
    private OrderPetAcquisition initOrderPetAcquisition(HandlerMsgDto handlerMsgDto, SearchMasterMsg searchMasterMsg, Pet pet) {

        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        // 调用工具类生成订单号
        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(searchMasterMsg.getUserId()));
        orderPetAcquisition.setDigest(handlerMsgDto.getNote());
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000));
        orderPetAcquisition.setPetId(pet.getId());
        orderPetAcquisition.setPrice(searchMasterMsg.getPrice());
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(searchMasterMsg.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(handlerMsgDto.getHandler());
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        return orderPetAcquisition;
    }

    /*
    * @Title: msg2Pet
    * @Description: 接单时生成宠物
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/20 16:55
    * @Parameters: [searchMasterMsg]
    * @Return cn.itlight.pet.domain.Pet
    */
    private Pet msg2Pet(SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setCostprice(searchMasterMsg.getPrice());
        pet.setTypeId(searchMasterMsg.getPetType());
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        return pet;
    }
}
